﻿#region Librerias

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Collections;

#endregion


namespace ESF.General
{
	public static class ObjectHelper
	{
		/// <summary>
		/// Perform a deep Copy of the object.
		/// </summary>
		/// <typeparam name="T">The type of object being copied.</typeparam>
		/// <param name="pSource">The object instance to copy.</param>
		/// <returns>The copied object.</returns>
		public static T Clone<T> (T pSource)
		{
			if (!typeof(T).IsSerializable)
			{
				throw new ArgumentException("The type must be serializable.", "pSource");
			}

			// Don't serialize a null object, simply return the default for that object
			if (Object.ReferenceEquals(pSource, null))
			{
				return default(T);
			}

			IFormatter formatter = new BinaryFormatter();

			Stream stream = new MemoryStream();

			using (stream)
			{
				formatter.Serialize(stream, pSource);
				stream.Seek(0, SeekOrigin.Begin);
				return (T)formatter.Deserialize(stream);
			}
		}


		public static IEnumerable<T> ToIEnumerable<T>(this IEnumerator<T> enumerator)
		{
			while (enumerator.MoveNext())
			{
				yield return enumerator.Current;
			}
		}


		public static IEnumerable<T> ToIEnumerable<T>(this IEnumerator enumerator)
		{
			while (enumerator.MoveNext())
			{
				yield return (T) enumerator.Current;
			}
		}
	} 
}